package org.hdl.anima.route;

import org.hdl.anima.Application;
import org.hdl.anima.common.module.BasicModule;
import org.hdl.anima.proxy.ServerProxy;
import org.hdl.anima.proxy.ServerProxys;
import org.hdl.anima.session.ISession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author qiuhd
 * @since  2014年8月5日
 */
public class Router extends BasicModule {

	private static final Logger logger = LoggerFactory.getLogger(Router.class);
	private ServerProxys serverProxys;
	private RouteTable routeTable;
	
	public Router(String moduleName) {
		super(moduleName);
	}

	@Override
	public String getName() {
		return super.getName();
	}

	@Override
	public void initialize(Application application) {
		super.initialize(application);
		this.routeTable = application.getMoulde(RouteTable.class);
		this.serverProxys = application.getMoulde(ServerProxys.class);
	}
	
	public void route(int msgId,byte[] msg,ISession sender) {
		
		String serverId = routeTable.getRoute(msgId);
		
		if (serverId == null) {
			throw new IllegalStateException("Failed to route this message,cause: Counld not found the server in routetable.message id :" + msgId);
		}
		
		ServerProxy proxy =  serverProxys.getServerProxy(serverId);
		
		if (proxy == null) {
			throw new IllegalStateException("Failed to route this message,cause: Counld not found the server proxy in server proxy.message id :" + msgId);
		}
		
		try {
			proxy.send(sender.getIdentity(), msg);
		}  catch (Exception e) {
			logger.error("Failed to send messaga to proxy,sender identity id :{} server proxy id :{}",sender.getIdentity(),serverId,e);
		}
	}
}

